package com.dingding.user.core.passenger.coupon.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.beans.UserCoupon;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.facde.activity.service.ICouponFacade;
import com.dingding.user.core.passenger.coupon.dao.IUserCouponDao;
import com.dingding.user.core.passenger.coupon.dao.sql.CouponDaoSQL;
import com.dingding.user.core.passenger.coupon.service.AbstractUserCouponService;
import com.dingding.user.core.passenger.coupon.service.IUserCouponService;
import com.dingding.user.core.passenger.user.service.IPassengerUserInfoService;

/**
 * 
 * @Description: 用户优惠券业务
 * @author CHEHUANBO
 * @date 2016年12月13日
 * @version V2.5.2
 * 
 */
@Component("_userCouponService")
public class UserCouponServiceImpl extends AbstractUserCouponService implements IUserCouponService {

	private static final Logger log = Logger.getLogger(UserCouponServiceImpl.class);

	@Resource(name = "_userCouponDao")
	private IUserCouponDao userCouponDao;

	@Resource(name = "_couponFacade")
	private ICouponFacade couponFacade;

	@Resource(name = "passengerUserInfoService")
	private IPassengerUserInfoService passengerUserInfoService;
	
	@Resource(name = "_userCouponService")
	private IUserCouponService userCouponService;

	@PostConstruct
	public void creteProducer() {

		// Properties properties = new Properties();
		// properties.put(PropertyKeyConst.ConsumerId,
		// MessageQueueConfig.getMESSAGE_QUEUE_BIZ_CONSUMERID());
		// properties.put(PropertyKeyConst.AccessKey,
		// Constants.MESSAGE_QUEUE_ACCESSKEY);
		// properties.put(PropertyKeyConst.SecretKey,
		// Constants.MESSAGE_QUEUE_SERECTKEY);
		// Consumer consumer = ONSFactory.createConsumer(properties);
		// consumer.subscribe(MessageQueueConfig.getMESSAGE_QUEUE_TOPIC(),
		// QueueTagsConstants.ADD_USER_COUPON,
		// new MessageListener() {
		// @Override
		// public Action consume(Message message, ConsumeContext context) {
		// try {
		//
		// log.info("读取到给用户添加优惠券消息消息, 消息ID" + message.getMsgID() + "消息内容："
		// + new String(message.getBody()));
		//
		// Map<String, Object> msgMap = JSONUtil.convertJsonStrToMap(new
		// String(message.getBody()));
		//
		// addUserCoupon(msgMap);
		//
		// return Action.CommitMessage;
		//
		// } catch (Exception e) {
		// log.error("读取队列消息给用户添加优惠券出现异常!", e);
		// return Action.ReconsumeLater;
		// }
		// }
		// });
		// consumer.start();

	}

	/**
	 * 
	 * @Description:添加用户优惠券
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	@Override
	public void addUserCoupon(Map<String, Object> queueMap) throws RuntimeException {

		int couponMoney = (int) queueMap.get("faceValue");
		int couponType = (int) queueMap.get("couponType");
		int couponId = (int) queueMap.get("couponId");
		Date expiredTime = DateFormatUtil.yyyy_MM_dd(String.valueOf(queueMap.get("endTime")));
		String userId = (String) queueMap.get("userId");

		int useScope = (int) queueMap.get("useScope");
		int enoughMoney = (int) queueMap.get("enoughMoney");
		int maximum = (int) queueMap.get("maximum");
		BigDecimal couponDiscounts = (BigDecimal) queueMap.get("couponDiscounts");
		int cityScope = (int) queueMap.get("cityScope");

		UserCoupon userCoupon = new UserCoupon();
		userCoupon.setCouponId(couponId); // 优惠券ID
		userCoupon.setUcId(UUID.randomUUID().toString()); // 主键ID
		userCoupon.setLoginId(userId); // 用户ID
		userCoupon.setCouponType(couponType); // 优惠券类型
		userCoupon.setCouponMoney(couponMoney); // 优惠券金额
		userCoupon.setExpiredTime(expiredTime); // 失效时间
		userCoupon.setCouponStatus(1); // 状态
		userCoupon.setUseScope(useScope); // 使用范围
		userCoupon.setEnoughMoney(enoughMoney); // 优惠金额
		userCoupon.setMaximum(maximum); // 最大优惠金额
		userCoupon.setCouponDiscounts(couponDiscounts); // 折扣
		userCoupon.setCityScope(cityScope); // 城市限制
		userCoupon.setCouponStatus(2); // 已激活
		userCoupon.setCreateTime(new Date());
		
		//执行添加用户优惠券
		userCouponService.excuteAddUserCoupon(userCoupon);

	}

	/**
	 * 
	 * @Description: 执行添加用户优惠券
	 * @date 2016年12月23日
	 * @author CHEHUANBO
	 * @version V2.6.4
	 * 
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
	public void excuteAddUserCoupon(UserCoupon userCoupon) {

		try {
			userCouponDao.addUserCoupon(userCoupon);
			passengerUserInfoService.updateUserCouponNumberAddOne(userCoupon.getLoginId());
		} catch (RuntimeException e) {
			log.error("出现异常执行添加用户优惠券，用户ID:" + userCoupon.getLoginId(), e);
		}

	}

	/**
	 * 
	 * @Description: 获取符合使用条件的用户优惠券
	 * 
	 *               此方法用户去支付时会调用
	 * 
	 * @param userId
	 *            用户ID
	 * @param produceType
	 *            产品类型
	 * @param cityNo
	 *            城市编号
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	@Override
	public UserCoupon getUserCoupon(String userId, int produceType, String cityNo) {

		if (StringUtils.isBlank(userId)) {
			throw new NullPointerException("通过用户ID获取用户有效优惠券被拒绝！原因：userId is null");
		}

		List<UserCoupon> userCouponList = null;
		try {

			userCouponList = userCouponDao.getUserCoupon(userId);

		} catch (Exception e) {
			log.error("通过用户ID获取当前用户有效优惠券出现异常！UserId:" + userId, e);
		}

		if (userCouponList != null && userCouponList.size() > 0) {

			for (UserCoupon userCoupon : userCouponList) {

				int couponType = userCoupon.getCouponType();

				// 验证优惠券类型
				switch (couponType) {
				case 1: // 洗车券
					break;
				case 2: // 现金券
					if (super.validateCashCoupon(userCoupon, produceType, cityNo)) {
						return userCoupon;
					}
					break;
				default: // 折扣券
					break;
				}

			}

		}

		return null;

	}

	/**
	 * 
	 * @Description: 锁定用户优惠券
	 * @param userCouponId
	 *            用户优惠券ID
	 * @param lockType
	 *            2：已激活 3：已使用 4：:禁止使用
	 * @author CHEHUANBO
	 * @version V2.6.2
	 * 
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED)
	public void lockUserCouponByCouponId(String userCouponId, int lockType) throws RuntimeException {

		if (StringUtils.isBlank(userCouponId) || lockType == 0) {
			throw new NullPointerException("锁定用户优惠券被拒绝! 参数存在空值！" + userCouponId);
		}
		super.getSqlBaseDao().updateSqLRow(CouponDaoSQL.LOCK_USER_COUPON, lockType, userCouponId);
	}

}
